package com.neuedu.mp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.neuedu.mp.entity.SysRole;
import com.neuedu.mp.entity.SysRoleMenu;
import com.neuedu.mp.entity.SysUserRole;
import com.neuedu.mp.mapper.SysRoleMapper;
import com.neuedu.mp.mapper.SysRoleMenuMapper;
import com.neuedu.mp.service.ISysRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neuedu.mp.vo.RoleMenuVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 角色信息表 服务实现类
 * </p>
 *
 * @author 金山老师
 * @since 2023-03-15
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {


    @Autowired
    SysRoleMenuMapper sysRoleMenuMapper;



    @Override
    public boolean grant(RoleMenuVO grant) {

        //先删除已经授权的信息
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("role_id"  , grant.getRoleId() );
        sysRoleMenuMapper.delete(queryWrapper);



        //再次授权
        int count = 0;
        for (Long menuId : grant.getMenuIds()) {
            SysRoleMenu entity = new SysRoleMenu();
            entity.setRoleId(grant.getRoleId());
            entity.setMenuId(menuId);
            count += sysRoleMenuMapper.insert(entity);
        }

        return count == grant.getMenuIds().length ;
    }

    @Override
    public List<Long> loadMenuIdsByRole(Long roleId) {
        return sysRoleMenuMapper.loadMenuIdsByRole(roleId);
    }
}
